package com.have.blog.xo.config;

import com.have.blog.base.constant.BlogConstant;
import com.have.blog.model.models.TCategoryMenu;
import com.have.blog.xo.service.admin.AdminLoginService;
import com.have.blog.xo.service.admin.AdminResourceService;
import com.have.haveblog.security.config.BaseSecurityConfig;
import com.have.haveblog.security.service.DynamicSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class AdminSecurityConfig extends BaseSecurityConfig {

    @Autowired
    private AdminLoginService adminLoginService;
    @Autowired
    private AdminResourceService adminResourceService;

    @Bean
    public UserDetailsService userDetailsService() {
        return username -> adminLoginService.loadAdminByUsername(username);
    }

    /**
     * 获取系统全部资源
     * @return
     */
    @Bean
    public DynamicSecurityService dynamicSecurityService() {
        return new DynamicSecurityService() {
            @Override
            public Map<String, ConfigAttribute> loadDataSource() {
                ConcurrentHashMap<String, ConfigAttribute> map = new ConcurrentHashMap<>();
                List<TCategoryMenu> categoryMenus = adminResourceService.listAll();
                for (TCategoryMenu categoryMenu : categoryMenus) {
                    map.put(categoryMenu.getUrl(), new org.springframework.security.access.SecurityConfig(categoryMenu.getName() + BlogConstant.SYMBOL_COLON + categoryMenu.getSummary()));
                }
                return map;
            }
        };
    }
}
